package org.cresource.basic.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 登录拦截器
 */
//@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        //判断是否登录？  前端需要给我们传递 token
        String token = request.getHeader("token");// fde6185f-36ac-4df0-9c0e-9d4c4ebb617c
        if(!StringUtils.isEmpty(token)){
            Object obj = redisTemplate.opsForValue().get(token);
            if(obj !=null){//已经登录过
                //刷新redis的token存储时间
                redisTemplate.opsForValue().set(token, obj, 30, TimeUnit.MINUTES);
                //放行
                return true;
            }
        }
        //如果已经登录过期
        response.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();

        //@TODO 权限校验
        return false;
    }
}
